package com.arch;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/*
 * Processor class 
 * Author:Tong.Zhi-Yong
 */
public class Processor extends Thread {
	private Socket socket;
	private InputStream in;
	private PrintStream out;
	public final static String WEB_ROOT = "f:\\httpdocs\\";
	
	public Processor(Socket socket) {
		this.socket = socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//get the file name from input stream from client
		String fileName = parseInput(in);
		sendBackContent(fileName);
	}
	
	public String parseInput(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String fileName = "";
		try {
			String queryStringFromClient = br.readLine();
			/*
			 * three part
			 * 1.code
			 * 2.request file name
			 * 3.version
			 */
			String[] content = queryStringFromClient.split(" ");
			
			if (content.length != 3) {
				sendErrorMessage(400, "client request error");
				return null;
			}
			
			fileName = content[1];
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return fileName;
	}
	
	public void sendErrorMessage(int errCode, String errMessage) {
		out.println("HTTP/1.0 " + errCode + " " + errMessage);
		out.println("content-type: text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Message");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode:" + errCode + ",Message:" + errMessage + "</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * back normal content
	 * @param fileName
	 */
	public void sendBackContent(String fileName) {
		File file = new File(Processor.WEB_ROOT + fileName);
		if (!file.exists()) {
			sendErrorMessage(404, "file not found");
			return;
		}
		
		try {
			InputStream in = new FileInputStream(file);
			byte[] content = new byte[(int) file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 SEND QUERY FILE");
			out.println("content-length:" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}